<template>
  <div class="product-choose">
    <div class="handel-header">
      <el-popover
        v-model="showPopover"
        placement="right-start"
        width="700"
        popper-class="no-padding-popover"
        trigger="click">

        <relative-card
          v-model="showPopover"
          :request-config="requestConfig"
          :default-value="productList"
          primary-key="productId"
          label="选择产品"
          @close="showPopover = !showPopover"
          @confirm="handleRelativeConfirm" />

        <el-button
          slot="reference"
          type="primary"
          size="mini"
          class="xr-btn--primary">
          添加产品
        </el-button>
      </el-popover>
    </div>

    <el-table
      :data="productList"
      style="width: 100%;">
      <template v-for="(field, index) in fieldList">
        <el-table-column
          :key="index"
          :prop="field.prop"
          :label="field.label"
          show-overflow-tooltip />
      </template>
      <el-table-column label="数量">
        <template slot-scope="scope">
          <el-input-number
            v-model="scope.row.saleProductNumber"
            :controls="false"
            :precision="2"
            :min="0"
            placeholder="请输入"
            @change="priceOrNumChange(scope)" />
        </template>
      </el-table-column>
      <el-table-column label="单价">
        <template slot-scope="scope">
          <el-input-number
            v-model="scope.row.saleProductPrice"
            :controls="false"
            :precision="2"
            placeholder="请输入"
            @input="priceOrNumChange(scope)" />
        </template>
      </el-table-column>
      <el-table-column label="折扣（%）">
        <template slot-scope="scope">
          <el-input-number
            v-model="scope.row.discount"
            :controls="false"
            :precision="2"
            placeholder="请输入"
            @input="priceOrNumChange(scope)" />
        </template>
      </el-table-column>
      <el-table-column
        prop="subtotal"
        label="合计"/>
      <el-table-column
        prop="saleProductSubtotal"
        label="整单折后价" />
      <el-table-column label="操作" width="100">
        <template slot-scope="scope">
          <el-button
            type="text"
            @click.stop="removeItem(scope.$index)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <flexbox class="handle-footer">
      <div class="discount-title">整单折扣（%）：</div>
      <el-input-number
        v-model="discountRate"
        :controls="false"
        :max="100"
        :precision="2"
        style="width: 80px"
        placeholder="请输入"
        type="number"
        @change="discountChange" />
      <div class="total-info">已选中产品：
        <span class="info-yellow">{{ totalCount }}</span>&nbsp;&nbsp;总金额：
        <el-input-number
          v-model="totalPrice"
          :controls="false"
          placeholder="请输入"
          style="width: 120px"
          @blur="totalPriceChange" />
        &nbsp;元
      </div>
    </flexbox>
  </div>
</template>

<script>
/**
 * Create by yxk at 2020/6/10
 */
import { jxcFieldQueryPageListAPI } from '@/api/jxc/field'
import RelativeCard from '../../RelativeCard'
import JxcTypes from '../../../jxcTypes'
import { objDeepCopy } from '@/utils'
import { accMul, accAdd, accSub } from '@/utils/acc'

export default {
  name: 'ProductChoose',
  components: {
    RelativeCard
  },
  props: {
    defaultValue: {
      type: Array,
      default: () => []
    },
    defaultRate: {
      type: [String, Number],
      default: 0
    }
  },
  data() {
    return {
      showPopover: false,

      fieldList: [
        { label: '产品名称', prop: 'productName', width: null },
        { label: '产品规格', prop: 'spDataValue', width: null },
        { label: '产品单位', prop: 'productCompany', width: null }
      ],
      productList: [],
      discountRate: 0,
      totalPrice: 0,
      totalCount: 0
    }
  },
  computed: {
    requestConfig() {
      return {
        fieldList: [
          { name: '产品名称', fieldName: 'productName' },
          { name: '产品规格', fieldName: 'spDataValue' },
          { name: '产品单位', fieldName: 'productCompany' },
          { name: '产品编号', fieldName: 'productCode' },
          { name: '市场价', fieldName: 'productMarketPrice' }
        ],
        listRequest: jxcFieldQueryPageListAPI,
        listParams: {
          label: JxcTypes.jxc_product.label,
          searchList: [{
            formType: 'text',
            type: 1,
            name: 'product_ishelf', // 上架的产品
            values: [1]
          }]
        },
        searchParamsFn: (params, keyword) => {
          if (keyword) {
            params.searchList.push({
              name: 'product_name',
              formType: 'text',
              type: 3,
              values: [keyword]
            })
          }
          return params
        }
      }
    }
  },
  watch: {
    defaultValue: {
      handler(val) {
        if (val.length > 0) {
          console.log('val default: ', val)
          this.productList = objDeepCopy(val).map(o => {
            return {
              ...o,
              discount: o.discount || 0
            }
          })
          // this.calcTotal()
        }
      },
      deep: true,
      immediate: true
    },
    defaultRate: {
      handler(val) {
        this.discountRate = Number(val) || 0
      },
      deep: true,
      immediate: true
    }
  },
  methods: {
    /**
     * 选择产品
     */
    handleRelativeConfirm(data) {
      // console.log('data', data)
      // console.log('productList', this.productList)
      const dataIds = data.valData
      // 去掉被删除的产品
      const productList = this.productList.filter(o => dataIds.includes(o.productId))
      // 过滤掉已经添加过的产品
      const ids = this.productList.map(o => o.productId)
      const list = data.data.filter(o => !ids.includes(o.productId)).map(o => {
        const price = o.productMarketPrice || o.productCostPrice || 0
        return {
          ...o,
          saleProductPrice: price,
          saleProductNumber: 1,
          saleProductSubtotal: price,
          discount: 0
        }
      })
      this.productList = [...productList, ...list]
      this.showPopover = false
      this.calcTotal()
    },

    /**
     * 修改单价/数量
     */
    priceOrNumChange(scope) {
      const row = scope.row
      const rate = (100 - this.discountRate || 0) / 100
      row.subtotal = accMul(row.saleProductPrice, row.saleProductNumber)
      row.subtotal = accMul(row.subtotal, (100 - row.discount || 0) / 100).toFixed(2)
      row.saleProductSubtotal = Number(accMul(row.subtotal, rate).toFixed(2))
      this.calcTotal()
    },
    discountChange() {
      const rate = (100 - this.discountRate || 0) / 100
      this.productList.forEach(o => {
        o.saleProductSubtotal = Number(accMul(o.subtotal, rate).toFixed(2))
      })
      this.calcTotal()
    },

    /**
     * 计算整单折扣准确值
     */
    preciseDiscountRate() {
      let realTotalPrice = 0
      this.productList.forEach(o => {
        realTotalPrice = accAdd(o.subtotal, realTotalPrice)
      })
      if (realTotalPrice === 0) return 0
      return accSub(100, (this.totalPrice / realTotalPrice * 100))
    },

    /**
     * 修改总价
     */
    totalPriceChange() {
      const preciseRate = this.preciseDiscountRate()
      this.discountRate = preciseRate.toFixed(2)
      const rate = (100 - preciseRate || 0) / 100
      this.productList.forEach(o => {
        o.saleProductSubtotal = Number(accMul(o.subtotal, rate).toFixed(2))
      })
      this.calcTotal()
      this.emitChange()
    },

    /**
     * 计算总价
     */
    calcTotal() {
      let res = 0
      this.productList.forEach(o => {
        res = accAdd(res, o.saleProductSubtotal)
      })
      this.totalPrice = res

      const arr = this.productList.map(o => o.saleProductNumber)
      let total = 0
      arr.forEach(num => {
        total += num
      })
      this.totalCount = total

      this.emitChange()
    },

    removeItem(index) {
      this.productList.splice(index, 1)
      this.calcTotal()
    },

    emitChange() {
      this.$emit('change', {
        data: this.productList,
        total: this.totalPrice,
        discount: this.discountRate
      })
    }
  }
}
</script>

<style scoped lang="scss">
  @import "index";
</style>
